#!/bin/bash

WORK_PATH="/opt/middleware/AtlasEdge"
SCRIPT_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/src/script"
backup_base_dir=$WORK_PATH/config/backup
file_list=`cat $SCRIPT_PATH/mod_file_list.txt`

. ${SCRIPT_PATH}/log_util.sh

#common resume file for sys_file and backup_file
common_file_resume()
{   
    for i in ${file_list}
    do
        target_file=$i
        backup_file=${backup_base_dir}/$(basename ${target_file})
        check_file=atlasedge_config_resume

        if [ -f ${backup_file}.md5 ]; then
            rm -f ${backup_file}.md5
        fi

        if [ ! -f ${backup_file}.checksum ] && [ ! -f ${backup_file} ] && [ -s ${target_file} ]; then
            #met a new backup file
            logger_Debug ":found a new backup file:$(basename ${target_file})!"
            #create dir for the new file
            mkdir -p `dirname ${backup_file}`
            #refresh verification for target file!
            sha256sum ${target_file} > /run/${check_file}.checksum
            dd if=/run/${check_file}.checksum of=${backup_file}.checksum conv=fsync status=none
            #upgrade backup file!
            dd if=${target_file} of=${backup_file} conv=fsync status=none
        else
            verify_fail=0
            if [ ! -s ${backup_file}.checksum ];then
                logger_Debug ":verification lost:${target_file}!"
                verify_fail=1
            else
                sha256sum -c ${backup_file}.checksum
                if [ $? -ne 0 ];then
                    logger_Info ":work file verify failed:$(basename ${target_file})!"
                    verify_fail=1
                else
                    verify_fail=0
                fi
            fi
            
            if [ $verify_fail -ne 0 ];then
                if [ ! -s ${backup_file} ];then
                    logger_Warn ":fatal error! backup file zero length or not exist:$(basename ${target_file})!"
                else
                    logger_Info ":resume work file:$(basename ${target_file})!"
                    #resume work file
                    dd if=${backup_file} of=${target_file} conv=fsync status=none
                    #refresh verification
                    logger_Info ":refresh verification:$(basename ${target_file})!"
                    sha256sum ${target_file} > /run/${check_file}.checksum
                    dd if=/run/${check_file}.checksum of=${backup_file}.checksum conv=fsync status=none
                fi
            else
                diff ${target_file} ${backup_file}
                if [ $? -ne 0 ];then
                    logger_Info ":upgrade backup file:$(basename ${target_file})!"
                    dd if=${target_file} of=${backup_file} conv=fsync status=none
                else
                    logger_Info ":work verify bakcup ok:$(basename ${target_file})!"
                fi
            fi
        fi
    done
}

common_file_resume
